﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GameLib.Utils;
using System.Reflection;

namespace GameLib.Gameplay.Scripting
{
	public abstract class ScriptMarkup
	{
		public ScriptMarkup()
		{
			ChildMarkups = new List<ScriptMarkup>();
		}

		public virtual void Load(ScriptReader reader)
		{
			reader.Read(); // read out the begin
			LoadAttributes(reader);
			LoadChildMarkups(reader);
			reader.Read(); // read out the end
		}

		public virtual void LoadAttributes(ScriptReader reader)
		{
			while (reader.CurrentNodeType == ScriptReaderNodeType.Attribute)
			{
				PropertyInfo pi = GetType().GetProperty(reader.AttrName);

				if (pi == null)
					throw new Exception(string.Format("Attribute {0} not found in type {1}", reader.AttrName, GetType()));
				pi.SetValue(this, StringConvert.FromString(reader.AttrValue, pi.PropertyType), null);
			}
		}

		public virtual void LoadChildMarkups(ScriptReader reader)
		{
			while (reader.CurrentNodeType != ScriptReaderNodeType.MarkupEnd)
			{
				ScriptMarkup markup = ScriptMarkups.FindMarkupInfo(reader.MarkupName).New();
				markup.Load(reader);
				ChildMarkups.Add(markup);
			}
		}

		public abstract Name Name { get; }
		protected List<ScriptMarkup> ChildMarkups { get; private set; }
	}
}
